import React, { useEffect, useState } from "react";
import { Navigate, useNavigate } from "react-router-dom";
import RBACManager from "../../utils/rbacManager";

export const PermissionGuard = ({
  children,
  permissions = [],
  roles = [],
  redirectTo = "/unauthorized",
}) => {
  const navigate = useNavigate();
  const [isChecking, setIsChecking] = useState(true);
  const [hasAccess, setHasAccess] = useState(false);

  useEffect(() => {
    checkAccess();
  }, []);
  const checkAccess = () => {
    try {
      // 首先检查是否已认证
      if (!RBACManager.isAuthenticated()) {
        console.log("User not authenticated");
        navigate("/login");
        return;
      }

      // 检查角色
      if (roles.length > 0) {
        const hasRole = roles.some((role) => RBACManager.hasRole(role));
        if (!hasRole) {
          console.log("Role check failed");
          setHasAccess(false);
          setIsChecking(false);
          return;
        }
      }

      // 检查权限
      if (permissions.length > 0) {
        const hasPermissions = permissions.every((permission) =>
          RBACManager.hasPermission(permission)
        );
        if (!hasPermissions) {
          console.log("Permission check failed");
          setHasAccess(false);
          setIsChecking(false);
          return;
        }
      }

      setHasAccess(true);
      setIsChecking(false);
    } catch (error) {
      console.error("Error checking permissions:", error);
      setHasAccess(false);
      setIsChecking(false);
    }
  };

  if (isChecking) {
    return <div>Loading...</div>; // 或者显示一个加载动画
  }

  if (!hasAccess) {
    return <Navigate to={redirectTo} replace />;
  }

  return children;
};
